<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row class="query-form" style="padding-top: 15px">
                <Col span="8">
                    <FormItem label="单位名称：" >
                        <cascaderDom ref="childOrg" @setOrgInfo="setOrgId1" @setOrgname="setOrgName1"
                                     :orgTree="true" :root-org-id="companyId"></cascaderDom>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label='荣誉级别：'>
                        <Select  v-model="honorLevelList" multiple style="width:100%;">
                            <Option v-for="item in honorLevels" :value="item.honorLevel" :key="item.honorLevel">{{ item.honorLevelName }}</Option>
                        </Select>
                    </FormItem>
                </Col>


                <Col span="8" v-if="!switchFlag">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset"  >重置</Button>
                    <Button   class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
                <Col span="8" v-else>
                    <FormItem label="获得时间：">
                        <DatePicker type="daterange" placement="bottom-end" v-model="form1.checkTime" style="width: 100%;"></DatePicker>
                    </FormItem>
                </Col>
            </Row>
            <Row  v-show="switchFlag" class="query-form" >
                <Col span="8">
                    <FormItem label="荣誉类型：">
                        <Select class="query-form-el"  v-model="honhorTypeList"  multiple style="width: 100%;">
                            <Option v-for="item in honhorTypes" :value="item.codingCodeId"
                                    :key="item.codingCodeId">{{ item.codingName }}
                            </Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="8" :offset="8">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reseter" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>

            <Row class="query-form">
                <Col span="24">
                    <Button size="large"  class="ivu-btn-add" icon="md-add"  @click="openSelect">新增</Button>
                    <Button type="primary" class="ivu-btn-add" :loading="buttonLoading1" icon="md-cloud-download"  @click="downloadFile">导出</Button>
                </Col>
            </Row>
        </Form>

        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据！"  :loading="buttonLoading" size="small"
               border :columns="columns1"  :data="dataTable" >
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24" >
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>

        <Modal  :title='add ? "工作荣誉信息新增":"工作荣誉信息修改"' :transfer=false v-model="model1"  :width=600 :styles="{height:'559px'}" class-name='limit-height-dialog'>
            <div>
                    <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom"  label-position="top">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem label="单位（个人）名称：" prop="honorOrgName">
                                   <Input type="text" v-model="form1datacopy.honorOrgName" ></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem label="荣获荣誉称号：" prop="honorName">
                                   <Input type="text" v-model="form1datacopy.honorName" ></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="发证机构：" prop="certAuth">
                                    <Input type="text" v-model="form1datacopy.certAuth" ></Input>
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="获得时间：" prop="certDate">
                                    <DatePicker class="query-form-el" type="date" format="yyyy-MM-dd"   v-model="form1datacopy.certDate"  placeholder="请选择"  style="width: 100%;"></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label="荣誉级别：" prop="hcmType">
                                        <Select class="query-form-el"  v-model="form1datacopy.honorLevel" label-in-value @on-change='hcmTypeChange'  style="width: 100%;">
                                            <Option v-for="item in honorLevels" :value="item.honorLevel" :key="item.honorLevel">{{ item.honorLevelName }}</Option>
                                        </Select>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="荣誉类型：" prop="honhorTypes">
                                    <Select class="query-form-el"  v-model="form1datacopy.honhorTypes" label-in-value @on-change='setSelect' multiple style="width: 100%;">
                                        <Option v-for="item in honhorTypes" :value="item.codingCodeId"
                                                :key="item.codingCodeId">{{ item.codingName }}
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem label="备注：">
                                    <Input v-model="form1datacopy.notes" type="textarea" :rows="4" />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                          <Col span="23">
                            <FormItem label="附件：">
                              <div>
                                <Upload ref="upload"
                                        :before-upload="beforeUpload1"
                                        :show-upload-list="true"
                                        :max-size="10240"
                                        multiple
                                        type="drag"
                                        :action="fileUrl">
                                  <div style="padding: 10px">
                                    <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                    <p>点击将文件拖拽到这里上传</p>
                                    <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                                  </div>
                                </Upload>
                              </div>
                              <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                <a @click="downloadFile1(form1datacopy.honorId,item)">{{ item.fileName }}</a>
                                <Button type="text" icon="md-trash" @click="remove1(item.id)"
                                        style="margin-left: 5px;margin-bottom: 3px"/>
                              </div>
                            </FormItem>
                          </Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="填写人：" prop="planStart">
                                    {{form1datacopy.createUserName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="创建时间：" prop="planEnd">
                                    {{form1datacopy.createDate}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem label="填写单位：">
                                    {{form1datacopy.companyName}}
                                </FormItem>
                            </Col>
                        </Row>

                    </Form>
            </div>
                    <div slot="footer">
                        <Button class='ivu-btn-save' :disabled="buttonDis" @click="submit('form1datacopy')" >确定</Button>
                        <Button class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                    </div>

        </Modal>
        <Modal title="工作荣誉信息详情" v-model="model2"  class="modal-view-detail"  :width=800 :styles="{height:'559px'}" class-name='limit-height-dialog'>

                    <Form  :model="showdata" :label-width="160" >
                        <Row type="flex" justify="space-around" >
                            <Col span="23" >
                                <FormItem label="单位（个人）名称：" prop="stdOrgName">
                                    {{form1datacopy.honorOrgName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" >
                            <Col span="23" >
                                <FormItem label="荣获荣誉称号：" prop="stdOrgName">
                                    {{form1datacopy.honorName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" >
                            <Col span="11" >
                                <FormItem label="发证机构：" >
                                     {{form1datacopy.certAuth}}
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="获得时间：">
                                    {{formatDate(new Date(form1datacopy.certDate), 'yyyy-MM-dd')}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" >
                            <Col span="11" >
                                <FormItem label="荣誉级别：" >
                                     {{form1datacopy.honorLevelName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="荣誉类型：" >
                                     {{form1datacopy.honhorTypeName}}
                                </FormItem>
                            </Col>

                        </Row>
                        <Row type="flex" justify="space-around" >
                            <Col span="23" >
                                <FormItem label="备注说明：" >
                                    {{form1datacopy.notes}}
                                </FormItem>
                            </Col>
                        </Row>
                      <Row type="flex" justify="space-around">
                        <Col span="23">
                          <FormItem label="附件：">
                            <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                              <a @click="downloadFile1(form1datacopy.honorId,item)">{{ item.fileName }}</a>
                            </div>
                          </FormItem>
                        </Col>
                      </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="填写人：" prop="planStart">
                                    {{form1datacopy.createUserName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="创建时间：" prop="planEnd">
                                    {{form1datacopy.createDate}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" >
                            <Col span="23" >
                                <FormItem label="填写单位：" >
                                    {{form1datacopy.companyName}}
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    <div slot="footer">
                        <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
                    </div>
        </Modal>

    </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import pageCommonFunction from '@/components/pageCommonFunction.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import {formatDate} from '@/tools/index'

var cascaderDom = () => import('@/components/cascader-dom.vue');
export default {
        components:{
            cascaderDom
        },
        data(){
            return{
                buttonDis: false,
                companyId: sessionStorage('userId').getObject('userId').companyId,
                fileUrl: Api.interestedPartiesUserFile,
                uploadList:[],
                form1: {
                },
                switchFlag:false,
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                honhorTypeList:[],
                honorLevels: [
                  {honorLevel: "1", honorLevelName: "国家级"},
                  {honorLevel: "2", honorLevelName: "省-直辖市级"},
                  {honorLevel: "3", honorLevelName: "区县级"},
                  {honorLevel: "5", honorLevelName: "地市级"},
                  {honorLevel: "4", honorLevelName: "集团级"},
                ],
                honhorTypes:[],
                dataTable:[],
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                     {
                        title: '单位（个人）名称',
                        minWidth: 300,
                        align: 'center',
                        key:'honorOrgName',
                    },
                    {
                        title: '荣获荣誉称号',
                        minWidth: 150,
                        align: 'center',
                        key:'honorName'
                    },
                    {
                        title: '荣誉级别',
                        minWidth: 150,
                        align: 'center',
                        key:'honorLevelName',
                    },
                    {
                        title: '荣誉类型',
                        minWidth: 150,
                        align: 'center',
                        key:'honhorTypeName',
                    },
                    {
                        title: '发证机构',
                        minWidth: 150,
                        align: 'center',
                        key:'certAuth',
                    },
                    {
                        title: '获得时间',
                        minWidth: 150,
                        align: 'center',
                        key:'certDate',
                        render:(h,params)=>{
                            return h('div',[
                                (this.formatDate(new Date(params.row.certDate), 'yyyy-MM-dd'))
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        minWidth: 200,
                        align: 'center',
                        render: (h, params) => {
                            let loginId = sessionStorage('userId').getObject('userId').userId

                            let deletable = params.row.createUserId===loginId || loginId ==='8ad810e24f39585c014f395aae380000' ||sessionStorage('userId').getObject('userId').userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined
                            // console.log('loginId1==',loginId)
                            // console.log('loginId2==',params.row.createUserId)
                            // console.log('loginId2==',deletable)
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params,1);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        marginLeft: '8px',
                                        color: !deletable ? '#d0d0d0' : '',
                                        pointerEvents: !deletable ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {

                                            this.showData(params,2);
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        marginLeft: '8px',
                                        color: !deletable ? '#d0d0d0' : 'red',
                                        pointerEvents: !deletable ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteData(params);
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    },

                ],
                ruleCustom : {
                    honorOrgName: [{
                        required: true,
                        message: '  ',
                        trigger: 'change'
                    }],
                    honorName: [{
                        required: true,
                        message: '  ',
                        trigger: 'change'
                    }],
                    certAuth: [{
                        required: true,
                        message: '  ',
                        trigger: 'change'
                    }],
                    hcmType: [{
                        validator: (rule, value, callback) => {
                            if (this.form1datacopy.honorLevel == null || this.form1datacopy.honorLevel == '' || this.form1datacopy.honorLevel == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    honhorTypes: [{
                        validator: (rule, value, callback) => {
                            if (this.form1datacopy.honhorTypes == null || this.form1datacopy.honhorTypes == '' || this.form1datacopy.honhorTypes == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    certDate: [{
                        validator: (rule, value, callback) => {
                            if (value == null || value == '' || value == undefined) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],

                },
                searchedDataToQuerythis:{},
                honorLevelList:[],
                exportUrl:Api.downloadReportHonorStatis,
                auditedOrgName:'',
                auditedOrgId:'',
                add:false,
                model1:false,
                model2:false,
                showdata: {},
                location:null,
                form1datacopy:{
                    appraiseScore:0,
                    appraiseRank:''
                },
                files :[],
                buttonLoading:false,
                buttonLoading1:false,
                tableHeight:10,
            }
        },
        mounted() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            //this.selectCodingSort();
            this.$http.get(Api.queryCodeDetailBySortId + '/RHS-000001', {params: {}}).then((res) => {
                this.honhorTypes = res.data.data;
            });
            this.query();
        },
        methods:{
            ...pageCommonFunction,
          remove1(id) {
            console.log(id)
            let url = this.fileUrl + '/file/' + id;
            this.$http.delete(url).then((res) => {
              this.getFiles1()
            })
          },
          beforeUpload1(file) {
            console.log(this.uploadList)
            let formData = new FormData();
            formData.append("files", file); // 文件对象
            let url = this.fileUrl + '/' + this.form1datacopy.honorId + '/files/guideFile'
            this.$http.post(url, formData).then((res) => {
              if (res.data.result == "success") {
                this.$Message.info("文件上传成功")
                this.getFiles1();
              }
            })
            return false
          },
          downloadFile1(guideId, file) {
            let url = this.fileUrl + '/file/' + file.id;
            this.$http.get(url, {
              responseType: 'blob'      //告诉服务器我们需要的响应格式
            }).then((res) => {
              console.log(res)
              const aLink = document.createElement("a");
              let blob = new Blob([res.data], {
                type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
              });
              aLink.href = URL.createObjectURL(blob)
              aLink.download = file.fileName //标题
              aLink.click()
              document.body.appendChild(aLink)
            })
          },
          getFiles1() {
            let url = this.fileUrl + '/' + this.form1datacopy.honorId + '/files/guideFile'
            this.$http.get(url).then((res) => {
              if (res.data.result == "success") {
                console.log(res.data)
                this.uploadList = res.data.data
              }
            })
          },

          onCancel() {
                this.model2 = false
            },
            setOrgId1(data) {
                this.form1.orgId = data[data.length - 1];
            },
            setOrgName1(data) {
                this.form1.orgName = data;
            },
            hcmTypeChange(appStatus) {
                if(appStatus){
                    this.form1datacopy.honorLevel = appStatus.value;
                    this.form1datacopy.honorLevelName = appStatus.label;
                }
            },
            setSelect(value) {
                this.form1datacopy.honhorTypeId = "";
                this.form1datacopy.honhorTypeName = "";
                for (let i = 0; i < value.length; i++) {
                    this.form1datacopy.honhorTypeId += value[i].value+",";
                    this.form1datacopy.honhorTypeName += value[i].label+"、";
                }
                this.form1datacopy.honhorTypeId = this.form1datacopy.honhorTypeId.slice(0,-1);
                this.form1datacopy.honhorTypeName = this.form1datacopy.honhorTypeName.slice(0,-1);
            },

            deleteData(params) {
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该条信息</p>',
                    okText: '确认',
                    onOk: () => {
                        let url = Api.deleteReportHonorStatis;
                        this.$http.get(url,  {params: {id:params.row.honorId}}).then((res) => {
                            if (res.status === 200) {
                                this.$Message.success('成功');
                                this.query()
                            }else if (res.data.status === 201) {
                                this.$Message.error(res.data.msg);

                            }
                        }).catch(e => {
                            this.$Message.error('请求失败' + e);
                        })
                    },
                    cancelText: '取消'
                });
            },

            openSelect(){
                this.form1datacopy={}
                // this.form1datacopy.honorLevel = "2"
                // this.form1datacopy.honorLevelName = "省市级"
                let userName = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserName"]
                this.form1datacopy.createDate= this.formatDate(new Date(), 'yyyy-MM-dd')
                this.form1datacopy.createUserName= userName
                this.form1datacopy.honorId = this.get_uuid();
                this.uploadList = [];
                let companyName = sessionStorage('userId').getObject('userId').companyName;
                this.form1datacopy.companyName= companyName
                this.model1 = true;
                this.add = true;
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            handleCancel() {
                this.form1datacopy = {

                };
                this.model1 = false;
            },
            selectCodingSort(){
                // this.$http.get(Api.queryCodeDetailBySortId + '/AS-000001', {params: {}}).then((res) => {
                //     this.appStatusList = res.data.data;
                // });
                // this.$http.get(Api.queryCodeDetailBySortId + '/REGION-000001', {params: {}}).then((res) => {
                //     this.locationList = res.data.data;
                // });
                // this.$http.get(Api.queryCodeDetailBySortId + '/SSL-000001', {params: {}}).then((res) => {
                //     this.stdRankList = res.data.data;
                // });
            },
            reset() {
                this.form1 = {};
                this.$refs.childOrg.resetCurrentOrg();
                this.honorLevelList = [];
                this.honhorTypeList = [];
                this.query();
            },
            query() {
                this.buttonLoading=true
                let userId = sessionStorage('userId').getObject('userId').userId;
                let initOrgId = sessionStorage('userId').getObject('userId').companyId;
                let createOrgId = this.form1.orgId || initOrgId
                let data = {
                    currentPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    createOrgId
                };
                this.form1.honorLevel ="";
                this.form1.honhorType ="";

                this.honorLevelList.forEach(item =>{

                    this.form1.honorLevel += item+","
                });
                this.honhorTypeList.forEach(item =>{

                    this.form1.honhorType += item+","
                });
                if (this.form1.honhorType) {
                    this.form1.honhorType = this.form1.honhorType.substring(0, this.form1.honhorType.lastIndexOf(','));
                }
                if (this.form1.checkTime&&this.form1.checkTime[0] != '') {
                    // let checkTime1 = new Date(this.form1.checkTime[0])
                    // this.form1.checkTime1 = checkTime1.getFullYear() + '-' + (checkTime1.getMonth() + 1) + '-' + checkTime1.getDate()
                     this.form1.checkTime1 = this.formatDate(new Date(this.form1.checkTime[0]), 'yyyy-MM-dd');
                    // let checkTime2 = new Date(this.form1.checkTime[1])
                    // this.form1.checkTime2 = checkTime2.getFullYear() + '-' + (checkTime2.getMonth() + 1) + '-' + checkTime2.getDate()
                     this.form1.checkTime2 = this.formatDate(new Date(this.form1.checkTime[1]), 'yyyy-MM-dd');
                }


                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
                //data.honorOrgName = this.form1.honorOrgName || ''
                //data.createUserId = userId
                let url = Api.queryReportHonorStatis;
                this.$http.get(url, {params: data}).then((res) => {
                    this.dataTable = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    console.log('this.pagedata.total',this.pagedata.total)
                    this.buttonLoading=false
                }).catch(e => {
                    console.error(e)
                    this.$Message.error("数据获取失败")
                })
            },
            showData(data, flag) {
                this.auditedOrgId  = data.row.auditedOrgId;
                this.auditedOrgName = data.row.auditedOrgName;
                data.row.certDate =  this.formatDate(new Date(data.row.certDate), 'yyyy-MM-dd')
                this.uploadList = [];
                data.row.createDate =  this.formatDate(new Date(data.row.createDate), 'yyyy-MM-dd')

                if (flag == 1) {
                  this.form1datacopy = JSON.parse(JSON.stringify(data.row));
                    this.getFiles1();
                    this.model2 = true;
                } else {
                    this.add = false;
                    this.form1datacopy = JSON.parse(JSON.stringify(data.row));
                    if (this.form1datacopy.honhorTypeId) {
                        this.form1datacopy.honhorTypes = this.form1datacopy.honhorTypeId.split(",");
                    }
                    this.getFiles1();
                    this.form1datacopy.certDate =  this.formatDate(new Date(this.form1datacopy.certDate), 'yyyy-MM-dd')
                    console.log(555,this.form1datacopy)
                    this.model1 = true;
                }
                //console.log(111,this.form1datacopy)
            },
            formatDate(date, fmt) {
                //console.log('date==',date)
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
               // console.log('date1==',fmt)
                return fmt;
            },

            submit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        //this.form1datacopy.planStart = this.formatDate(new Date(this.form1datacopy.planStart), 'yyyy-MM-dd');
                        //this.form1datacopy.planEnd = this.formatDate(new Date(this.form1datacopy.planEnd), 'yyyy-MM-dd');
                            this.buttonDis = true;
                            if(this.add){
                                let userId = sessionStorage('userId').getObject('userId').userId;
                                let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                                let orgName = sessionStorage('userId').getObject('userId').orgInfo.orgName;
                                this.form1datacopy.createUserId = userId;
                                this.form1datacopy.createOrgId = orgId;
                                this.form1datacopy.createOrgName = orgName;
                                this.form1datacopy.certDate =  this.formatDate(new Date(this.form1datacopy.certDate), 'yyyy-MM-dd')
                                this.$http.post(Api.createReportHonorStatis, this.form1datacopy).then((res) => {

                                    if (res.status === 200) {
                                        this.$Message.success('成功');
                                        this.model1 = false;
                                        this.query()

                                    }else if (res.data.status === 201) {
                                        this.$Message.error(res.data.msg);
                                        this.model1 = false;
                                    }
                                    this.buttonDis = false;
                                }).catch(e => {
                                    this.buttonDis = false;
                                    this.model1 = false;
                                    this.query();
                                    this.$Message.error("数据获取失败")
                                })
                            }else{
                                let userId = sessionStorage('userId').getObject('userId').userId;
                                let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                                this.form1datacopy.certDate =  this.formatDate(new Date(this.form1datacopy.certDate), 'yyyy-MM-dd')
                                this.form1datacopy.updateUserId = userId;
                                this.form1datacopy.updateOrgId = orgId;
                                this.$http.post(Api.updateReportHonorStatis, this.form1datacopy).then((res) => {
                                    if (res.status === 200) {
                                        this.$Message.success('成功');
                                        this.model1 = false;
                                        this.query()

                                    }else if (res.data.status === 201) {
                                        this.$Message.error(res.data.msg);
                                        this.model1 = false;
                                    }
                                    this.buttonDis = false;
                                }).catch(e => {
                                    this.buttonDis = false;
                                    this.model1 = false;
                                    this.query();
                                    this.$Message.error("数据获取失败")
                                })
                            }


                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 44;

                } else {
                    this.tableHeight = this.tableHeight - 44;
                }

            },
            reseter() {
                this.form1 = {};
                this.$refs.childOrg.resetCurrentOrg();
                this.honorLevelList = [];
                this.honhorTypeList = [];
                this.query();
            },
            downloadFile() {
                this.buttonLoading1=true
                let userId = sessionStorage('userId').getObject('userId').userId;
                let initOrgId = sessionStorage('userId').getObject('userId').companyId;
                let createOrgId = this.form1.orgId || initOrgId
                let data = {
                    createOrgId
                };
                this.form1.honorLevel ="";

                this.honorLevelList.forEach(item =>{

                    this.form1.honorLevel += item+","
                });
                if (this.form1.checkTime&&this.form1.checkTime[0] != '') {
                    // let checkTime1 = new Date(this.form1.checkTime[0])
                    // this.form1.checkTime1 = checkTime1.getFullYear() + '-' + (checkTime1.getMonth() + 1) + '-' + checkTime1.getDate()
                    this.form1.checkTime1 = this.formatDate(new Date(this.form1.checkTime[0]), 'yyyy-MM-dd');
                    // let checkTime2 = new Date(this.form1.checkTime[1])
                    // this.form1.checkTime2 = checkTime2.getFullYear() + '-' + (checkTime2.getMonth() + 1) + '-' + checkTime2.getDate()
                    this.form1.checkTime2 = this.formatDate(new Date(this.form1.checkTime[1]), 'yyyy-MM-dd');
                }

                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
                this.$http.get(this.exportUrl, {
                    params:data,
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = "工作荣誉统计表("+formatDate(new Date(), "yyyy-MM-dd")+").xlsx" //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                    this.buttonLoading1=false
                })
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
            get_uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (let i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
                s[8] = s[13] = s[18] = s[23] = "-";

                let uuid = s.join("");
                let reg = new RegExp("-", "g");
                let a = uuid.replace(reg, "");
                console.log(a);
                return a;
            },
        },
        watch:{
            "model1":function(qw,er){
                if(qw && this.model1){
                    setTimeout(()=>{
                        //this.$refs.trainOrg.setCurrentOrg();

                    },100)
                }else{
                    //this.$refs.trainOrg.setCurrentOrg();

                }
            }

        }
    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';
</style>
